import axios from 'axios';
import { getAuth } from './storage';
import { Toast } from 'antd-mobile';

export const baseURL = 'http://geek.itheima.net';

const request = axios.create({
  baseURL,
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(config => {
  const { token } = getAuth()
  // 若已登录,携带token
  token && (config.headers.Authorization = `Bearer ${token}`)
  return config;
}, err => {
  return Promise.reject(err);
})

// 响应拦截器
request.interceptors.response.use(res => {
  return res.data;
}, err => {
  if (err.response && err.response.status === 401) {
    Toast.show({ content: '用户身份已过期,请重新登录' })
    window.location.href = '/login'
  }
  return Promise.reject(err);
})

export default request